﻿using MediatR;
using Microsoft.EntityFrameworkCore.Metadata;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.RoleMenuFunCommand;
using RBAC_Uthorization.Read.API.DTO;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.RoleMenuFunHandler
{
    public class RoleMenuFunIdCommandHandlers : IRequestHandler<RoleMenuFunIdCommand, ApiResult<string[]>>
    {
        private readonly IFunctionRepository _functionRepository;
        private readonly IRoleMenuFuncRepository _roleMenuFuncRepository;
        private readonly ILogger<RoleMenuFunIdCommandHandlers> _logger;

        public RoleMenuFunIdCommandHandlers(ILogger<RoleMenuFunIdCommandHandlers> logger, IRoleMenuFuncRepository roleMenuFuncRepository, IFunctionRepository functionRepository)
        {
            _logger = logger;
            _roleMenuFuncRepository = roleMenuFuncRepository;
            _functionRepository = functionRepository;
        }

        public async Task<ApiResult<string[]>> Handle(RoleMenuFunIdCommand request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(request.MenuId.ToString()))
            {
                return new ApiResult<string[]>();
            }
            var roleIds = request.RoleId.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            var roleMenuFuncs = await _roleMenuFuncRepository.GetAllAsunc(x => roleIds.Contains(x.role_id)&&x.menu_id==request.MenuId);
            var functionIds = roleMenuFuncs.Select(x => x.fun_id).ToList();
            var functions = await _functionRepository.GetAllAsunc(x => functionIds.Contains(x.id));
            var functionCodes = functions.Select(x => x.perms).ToArray();
            return new ApiResult<string[]>() { Data= functionCodes};
        }
    }
}
